var ws;
var address = "ws://10.0.1.3:2222/example/chat";
var currentName = "";
$(function () {
    registerbtn();
    clearbtn();
    sendbtn();
    $("#name").keydown(function(event){
        if (event.keyCode == 13){
            $("input[name='register']").click()
        }
    })
})


function clearbtn() {
    $("input[name='clear']").click(function () {
        $("textarea[name='msg']").val("");
    })
}

function sendbtn() {
    $("input[name='send']").click(function () {
        var msg = $("textarea[name='msg']").val();
        if (!msg) {
            alert("你不想说点什么吗？");
        } else {
            to_name = $("input[name='send_name']").val()
            if(to_name == currentName){
                alert("do not send message to myself")
                return
            }
            ws.send($.toJSON({"message":msg, "_mapping":"sendMsg", "name": to_name}));
            $("textarea[name='msg']").val("");
        }
    })
}

function registerbtn() {
    $("input[name='register']").click(function () {
        currentName = $("#name").val();
        if (!currentName) {
            alert("需要输入一个昵称");
        } else {
            onopen = function () {
                var msg = $("<h1>").html("欢迎:" + currentName + "<button style='float:right;margin-right:50px' onclick='logout()'>退出</button>");
                $("#msg_content header").empty().append(msg);
                $("#msgRegion").show();
                ws.send($.toJSON({"message":currentName}))
            }

            onclose = function () {
                alert("服务器已断开连接");
                window.location.reload()
            };
            ws = openWebsocket(address + "?ws_user=" + currentName, onopen, onclose)
        }
    })
}

function logout() {
    ws.send($.toJSON({"_mapping":"logout"}));
}

function exit(data){
    var user = data.user
    alert("用户"+user+"已经退出")
    $("#user_list ul li[id='"+user+"']").remove();
}

function addUser(data) {
    var userList = data.users
    var list = $("#user_list ul");
    list.empty();

    $.each(userList, function (n, value) {
        oneLine = "<li id='"+value+"'>" + value+ "</li>";
        list.append(oneLine);
    })
}

function addMsg(data) {
    var user = data.speaker
    var content = data.message
    if (user && content) {
        var msg = [];

        //add title
        msg.push("<li>");
        msg.push("<h2>");
        msg.push(user);
        msg.push(" <time>");
        msg.push(getNow());
        msg.push("</time>");
        if (data.receiver){
            if (data.receiver == currentName)
                msg.push(" [ only to you ]");
            else
                msg.push(" [ only to " + data.receiver + " ]");
        }else{
            msg.push(" [ to all ]");
        }
        msg.push("</h2>");
        //add content
        msg.push("<pre>");
        msg.push(content);
        msg.push("</pre>");
        msg.push("</li>");
        $("#container ul").append(msg.join(""));

    }
}


